// Copyright (c) XiGuan 2023
// Author： xiguan
// Email: xiguan.teng@qq.com
// Create on 2023/11/2
// TODO:
//

#ifndef WEBSERVER_POOLS_SQLCONNPOOL_H
#define WEBSERVER_POOLS_SQLCONNPOOL_H

#include <mysql/mysql.h>
#include <semaphore.h>

#include <mutex>
#include <queue>

class SqlConnPool {
 private:
  SqlConnPool();
  ~SqlConnPool();

  int MAX_CONN_;
  int use_count_;
  int free_count_;

  std::queue<MYSQL *> conn_queue_;
  std::mutex mtx_;
  sem_t sem_id_;

 public:
  /**
   * @brief 返回单例的实例
   * @return
   */
  static SqlConnPool *Instance();

  MYSQL *GetConn();

  /**
   * @brief 用完连接之后重新放回数据库连接池
   * @param conn 单个连接
   */
  void free_conn(MYSQL *conn);

  int GetFreeConnCount();

  /**
   * @brief 初始化连接信息
   * @param host
   * @param port
   * @param user
   * @param password
   * @param db_name
   * @param conn_size
   */
  void init(const char *host, int port, const char *user, const char *password,
            const char *db_name, int conn_size);

  void close_pool();
};

#endif  // WEBSERVER_POOLS_SQLCONNPOOL_H
